package com.suntine.familytree.businessunit.regiester.controller;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.suntine.familytree.businessunit.regiester.assistant.RegisterForm;
import com.suntine.familytree.businessunit.regiester.service.RegisterService;
import com.suntine.familytree.core.business.user.entity.User;
import com.suntine.familytree.core.framework.component.message.Message;
import com.suntine.familytree.core.framework.component.message.MessageType;
import com.suntine.familytree.core.framework.controller.BaseController;
import com.suntine.familytree.core.framework.util.AjaxUtils;
import com.suntine.familytree.util.RefUtils;

@Controller
@RequestMapping(value="register")
public class RegisterController extends BaseController{
	
	@Autowired
	RegisterService rs;
	
	public RegisterController() {
		super();
		// TODO Auto-generated constructor stub
		this.initLogger(this.getClass());
	}

	@RequestMapping(value="page",method=RequestMethod.GET)
	public String register(@RequestHeader(value="X-Requested-With", required=false) String requestedWith,Model model,HttpSession session){
		model.addAttribute("registerForm",new RegisterForm());
		model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(requestedWith));
		return "/register/register";
	}
	
	@RequestMapping(value="create",method=RequestMethod.POST)
	public String onRegister(@RequestHeader(value="X-Requested-With", required=false) String requestedWith,@ModelAttribute("registerForm") @Valid RegisterForm registerForm,BindingResult result,HttpSession session,Model model){
		if(result.hasErrors()) {
			model.addAttribute("message",new Message(MessageType.error,result.getAllErrors().get(0).getDefaultMessage()));
			model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(requestedWith));
			return "/register/register";
		}else{
			User user = new User();
			RefUtils.simpleCopyA2B(registerForm, user);
			rs.save(user);
			return "/pure_success";
		}
	}
}
